package com.alogic.es.xscript;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.ExtensionTag;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.XmlTools;
import org.w3c.dom.Element;

/**
 * 指令
 *
 * @since 1.6.13.9 [20200824 duanyy]
 */
public class EsCommand extends ExtensionTag {
    protected Logiclet callbackRequest = null;
    protected Logiclet callbackResponse = null;

    protected String callbackRequestId = "$es-callback-request";
    protected String callbackResponseId = "$es-callback-response";

    public EsCommand(String tag, Logiclet p) {
        super(tag, p);
    }

    public EsCommand(String tag, Logiclet p, String src) {
        super(tag, p,src);
    }

    @Override
    public void configure(Properties p) {
        super.configure(p);
        callbackRequestId = PropertiesConstants.getString(p,"requestId",callbackRequestId,true);
        callbackResponseId = PropertiesConstants.getString(p,"responseId",callbackResponseId,true);
    }

    @Override
    public void configure(Element root, Properties p) {
        super.configure(root, p);
        Element elem = XmlTools.getFirstElementByPath(root,"on-request");
        if (elem != null){
            callbackRequest = createLogiclet("segment",this);
            callbackRequest.configure(elem,p);
        }

        elem = XmlTools.getFirstElementByPath(root,"on-response");
        if (elem != null){
            callbackResponse = createLogiclet("segment",this);
            callbackResponse.configure(elem,p);
        }
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        if (script == null){
            log(String.format("[%s]Script is null ,ignored..",this.getXmlTag()),"warnning");
            return ;
        }
        try {
            if (callbackRequest != null) {
                ctx.setObject(callbackRequestId, callbackRequest);
            }
            if (callbackResponse != null) {
                ctx.setObject(callbackResponseId, callbackResponse);
            }

            script.execute(root, current, ctx, watcher);
        }finally{
            ctx.removeObject(callbackRequestId);
            ctx.removeObject(callbackResponseId);
        }
    }

    @Override
    protected void onStart(LogicletContext ctx, LogicletContext childCtx) {
        // nothing to do
    }

    @Override
    protected void onEnd(LogicletContext ctx, LogicletContext childCtx) {
        // nothint to do
    }
}